<template>
  <div class="cart">
    <h4>全部商品</h4>
    <div class="cart-main">
      <div class="cart-th">
        <div class="cart-th1">全部</div>
        <div class="cart-th2">商品</div>
        <div class="cart-th3">单价（元）</div>
        <div class="cart-th4">数量</div>
        <div class="cart-th5">小计（元）</div>
        <div class="cart-th6">操作</div>
      </div>
      <div class="cart-body">
        <ul
          class="cart-list"
          v-for="cartInfo in cartInfoList"
          :key="cartInfo.id"
        >
          <li class="cart-list-con1">
            <input
              type="checkbox"
              name="chk_list"
              :checked="cartInfo.isChecked === 1"
              @input="isCheckedChange(cartInfo)"
            />
          </li>
          <li class="cart-list-con2">
            <img :src="cartInfo.imgUrl" />
            <div class="item-msg">
              {{ cartInfo.skuName }}
            </div>
          </li>
          <li class="cart-list-con3">
            <div class="item-txt">语音升级款</div>
          </li>
          <li class="cart-list-con4">
            <span class="price">{{ cartInfo.skuPrice }}</span>
          </li>
          <li class="cart-list-con5">
            <a class="mins" @click="goodsNumChange(cartInfo, -1)"> - </a>
            <input
              autocomplete="off"
              type="text"
              :value="cartInfo.skuNum"
              @input="changeSkuNumDebu($event, cartInfo)"
              minnum="1"
              class="itxt"
            />
            <a class="plus" @click="goodsNumChange(cartInfo, 1)">+</a>
          </li>
          <li class="cart-list-con6">
            <span class="sum">{{ cartInfo.skuPrice * cartInfo.skuNum }}</span>
          </li>
          <li class="cart-list-con7">
            <a class="sindelet" @click="cartGoodsDelete(cartInfo.skuId)"
              >删除</a
            >
            <br />
            <a href="#none">移到收藏</a>
          </li>
        </ul>
      </div>
    </div>
    <div class="cart-tool">
      <div class="select-all">
        <input class="chooseAll" type="checkbox" v-model="allChange" />
        <span>全选</span>
      </div>
      <div class="option">
        <a @click="CartdeleteCheckGoods">删除选中的商品</a>
        <a href="#none">移到我的关注</a>
        <a href="#none">清除下柜商品</a>
      </div>
      <div class="money-box">
        <div class="chosed">
          已选择 <span>{{ allCheck }}</span
          >件商品
        </div>
        <div class="sumprice">
          <em>总价（不含运费） ：</em>
          <i class="summoney">{{ allPrise }}</i>
        </div>
        <div class="sumbtn">
          <router-link class="sum-btn" to="/trade">结算</router-link>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import {
  getGoodList,
  changeIsChecked,
  deleteCartGoods,
  goodsChangeAll,
  addGoodscat,
  deleteCartCheckGoods,
} from '@/api'
import { debounce } from 'lodash'
export default {
  name: 'ShopCart',
  data() {
    return {
      cartInfoList: [],
    }
  },
  mounted() {
    this.goodListGet()
    this.changeSkuNumDebu = debounce(this.changeSkuNum, 400)
  },
  computed: {
    allChange: {
      get() {
        return (
          this.cartInfoList &&
          this.cartInfoList.every((item) => {
            return item.isChecked === 1
          })
        )
      },
      async set(newVal) {
        //当修改多选框时,根据修改到的值发送请求修改全部的商品
        // 并重新发送请求渲染数据
        try {
          let skuId = this.cartInfoList.map((item) => {
            return item.skuId
          })
          await goodsChangeAll(newVal ? 1 : 0, skuId)
          this.goodListGet()
        } catch (error) {
          alert(error.message)
        }
      },
    },
    // 通过计算属性计算出总个数以及总价钱
    allCheck() {
      // reduce计算属性

      return this.cartInfoList?.reduce((q, c) => {
        // 直接输入input框中的值是string类型,直接运算会拼接
        // 需要过滤未选中的数据
        if (c.isChecked === 1) {
          return q + c.skuNum * 1
        }
        return q
      }, 0)
    },
    allPrise() {
      return this.cartInfoList?.reduce((q, c) => {
        // 直接输入input框中的值是string类型,直接运算会拼接
        if (c.isChecked === 1) {
          return q + c.skuPrice * c.skuNum
        }
        return q
      }, 0)
    },
  },
  methods: {
    async goodListGet() {
      try {
        let re = await getGoodList()
        // 当数据全部删除时不应该渲染页面
        let newcartInfoList = re[0]?.cartInfoList.map((item) => {
          item.flag = false
          item.oldSkuNum = item.skuNum
          return item
        })
        this.cartInfoList = newcartInfoList
      } catch (error) {
        alert(error)
      }
    },
    // 点击发送修改选中状态的请求
    async isCheckedChange(cartInfo) {
      let { isChecked, skuId } = cartInfo
      try {
        await changeIsChecked(skuId, isChecked === 1 ? 0 : 1)
        this.goodListGet()
      } catch (error) {
        console.log(error)
      }
    },
    // 单个删除
    async cartGoodsDelete(skuId) {
      try {
        await deleteCartGoods(skuId)
        this.goodListGet()
        alert('删除成功')
      } catch (error) {
        console.log(error.message)
      }
    },
    // 批量修改

    // 修改购买数量
    async goodsNumChange(cartInfo, num) {
      if (cartInfo.flag) return
      cartInfo.flag = true
      if (cartInfo.skuNum + num <= 0) return (cartInfo.flag = false)
      try {
        await addGoodscat(cartInfo.skuId, num)
        // 3.但是函数中有很多异步函数,当正常执行时flag修改会在其渲染之前,就会导致渲染过程中再次渲染偏离正常值
        // 4.async函数返回的是一个promise对象,当内部的函数执行完毕后,会返回一个成功proimise对象
        // 所以其也可以使用await

        await this.goodListGet() //使后面的数据修改等待
        // 2.flag进行节流处理,当数据请求过程还在渲染时,flag就为true,整个过程就不会进行第二遍,只有当全部执行完毕后,才能将其修改为false
        // 代表可以下一次修改
        cartInfo.flag = false
      } catch (error) {
        console.log(error.message)
        cartInfo.flag = false
      }
    },
    // 直接输入SkuNum值
    async changeSkuNum(e, cartInfo) {
      const reg = /^[1-9]+$/
      if (reg.test(e.target.value)) {
        let changeNUms = e.target.value - cartInfo.oldSkuNum
        await addGoodscat(cartInfo.skuId, changeNUms)
        cartInfo.skuNum = e.target.value
        cartInfo.oldSkuNum = cartInfo.skuNum
      } else {
        e.target.value = cartInfo.oldSkuNum
        cartInfo.skuNum = cartInfo.oldSkuNum
      }
    },
    // 直接输入的防抖占位函数
    changeSkuNumDebu() {},
    //删除选中数据
    async CartdeleteCheckGoods() {
      // reduce在筛选出数组对象中的固定项,而不是筛选整个对象时拥有奇效
      // 比如需要筛选指定规则中的id,然后用其id组成一个新的数组
      // 这时使用map会出现长度不对,使用filter会筛选出整个对象
      // 这时用reduce,设置起始值[],然后q代表起始值,一直向p中添加数值,并返回其,遍历结束后就能直接生成id数组
      // 使用forEach,在外部创建一个新数组,然后添加合格的值也和这差不多,但是实现方式很新奇
      let deleteList = this.cartInfoList?.reduce((q, c) => {
        if (c.isChecked === 1) {
          q.push(c.skuId)
        }
        return q
      }, [])
      console.log(deleteList)
      try {
        await deleteCartCheckGoods(deleteList)
      } catch (error) {
        console.log(error.message)
      }
    },
  },
}
</script>

<style lang="less" scoped>
.cart {
  width: 1200px;
  margin: 0 auto;

  h4 {
    margin: 9px 0;
    font-size: 14px;
    line-height: 21px;
  }

  .cart-main {
    .cart-th {
      background: #f5f5f5;
      border: 1px solid #ddd;
      padding: 10px;
      overflow: hidden;

      & > div {
        float: left;
      }

      .cart-th1 {
        width: 25%;

        input {
          vertical-align: middle;
        }

        span {
          vertical-align: middle;
        }
      }

      .cart-th2 {
        width: 25%;
      }

      .cart-th3,
      .cart-th4,
      .cart-th5,
      .cart-th6 {
        width: 12.5%;
      }
    }

    .cart-body {
      margin: 15px 0;
      border: 1px solid #ddd;

      .cart-list {
        padding: 10px;
        border-bottom: 1px solid #ddd;
        overflow: hidden;

        & > li {
          float: left;
        }

        .cart-list-con1 {
          width: 4.1667%;
        }

        .cart-list-con2 {
          width: 25%;

          img {
            width: 82px;
            height: 82px;
            float: left;
          }

          .item-msg {
            float: left;
            width: 150px;
            margin: 0 10px;
            line-height: 18px;
          }
        }

        .cart-list-con3 {
          width: 20.8333%;

          .item-txt {
            text-align: center;
          }
        }

        .cart-list-con4 {
          width: 12.5%;
        }

        .cart-list-con5 {
          width: 12.5%;

          .mins {
            border: 1px solid #ddd;
            border-right: 0;
            float: left;
            color: #666;
            width: 6px;
            text-align: center;
            padding: 8px;
          }

          input {
            border: 1px solid #ddd;
            width: 40px;
            height: 33px;
            float: left;
            text-align: center;
            font-size: 14px;
          }

          .plus {
            border: 1px solid #ddd;
            border-left: 0;
            float: left;
            color: #666;
            width: 6px;
            text-align: center;
            padding: 8px;
          }
        }

        .cart-list-con6 {
          width: 12.5%;

          .sum {
            font-size: 16px;
          }
        }

        .cart-list-con7 {
          width: 12.5%;

          a {
            color: #666;
          }
        }
      }
    }
  }

  .cart-tool {
    overflow: hidden;
    border: 1px solid #ddd;

    .select-all {
      padding: 10px;
      overflow: hidden;
      float: left;

      span {
        vertical-align: middle;
      }

      input {
        vertical-align: middle;
      }
    }

    .option {
      padding: 10px;
      overflow: hidden;
      float: left;

      a {
        float: left;
        padding: 0 10px;
        color: #666;
      }
    }

    .money-box {
      float: right;

      .chosed {
        line-height: 26px;
        float: left;
        padding: 0 10px;
      }

      .sumprice {
        width: 200px;
        line-height: 22px;
        float: left;
        padding: 0 10px;

        .summoney {
          color: #c81623;
          font-size: 16px;
        }
      }

      .sumbtn {
        float: right;

        a {
          display: block;
          position: relative;
          width: 96px;
          height: 52px;
          line-height: 52px;
          color: #fff;
          text-align: center;
          font-size: 18px;
          font-family: 'Microsoft YaHei';
          background: #e1251b;
          overflow: hidden;
        }
      }
    }
  }
}
</style>
